import React from 'react';
import { TabNavigator } from 'react-navigation';
import {
  View,
  Platform,
  StyleSheet,
  Image,
  Text,
  TouchableOpacity,
} from 'react-native';
import CookieManager from 'react-native-cookies';
import _ from 'lodash';
import PxToDp from '../../utils/PxToDp';
import Modalext from '../Public/ModalExt';
import SaleChance from '../../containers/SaleChanceListContainer';
import MyCustomer from '../../containers/myCustomerListContainer';
import OtherCustomer from '../../containers/OtherListContainer';
// import ChannelUser from './ChannelUser';
import SaleChanceFilter from '../../containers/SaleChanceFilterContainer';
import MyCustomerFilter from '../../containers/MyCustomerFilterContainer';
import OtherCustomerFilter from '../../containers/OtherCustomerFilterContainer';
import ChanelFilter from '../../containers/ChanelFilterContainer';
import FontFamilys from '../../utils/FontFamilys';
import { fetchMyCustomerList, fetchSaleList } from '../../actions/SaleListActions';
import Login from '../../containers/LoginContainer';


/* global homeWs */
/* global homeWS_URL */
global.homeWs = null;
// global.homeWS_URL = 'wss://api.autoforce.net/ws/dealer/upline/dynamic/users';
global.homeWS_URL = 'wss://dms.autoforce.net/ws/dealer/upline/dynamic/users';
// global.homeWS_URL = 'wss://http://192.168.9.24:3000/ws/dealer/upline/dynamic/users';


let pageIndex = 0;
let msid = '';

const Routes = {
  移动数字经销店: { screen: SaleChance },
  我的客户: { screen: MyCustomer },
  他人客户: { screen: OtherCustomer },
};

const TabConfig = {
  stateName: 'MainNavigation',
  lazy: true, // 是否懒加载
  initialRouteName: '移动数字经销店',
  tabBarPosition: 'top',
  animationEnabled: false,
  swipeEnabled: true,
  ...TabNavigator.Presets.AndroidTopTabs,
  tabBarOptions: {
    activeTintColor: '#121212', // 当前活动tab字体颜色
    inactiveTintColor: '#666',  // 默认字体颜色
    indicatorStyle: {
      borderBottomColor: '#121212',
      borderBottomWidth: 3,
      width: PxToDp(12),
      marginLeft: PxToDp(67),
    },
    scrollEnabled: true,
    showIcon: false,
    pressOpacity: 0.8,
    style: {
      height: 44,
      backgroundColor: '#fff',
      elevation: 0,
      borderColor: '#e8e8e8',
      borderStyle: 'solid',
      borderBottomWidth: PxToDp(0.5),
    },
    labelStyle: {
      fontSize: 14,
      fontFamily: FontFamilys(),
    },
    tabStyle: {
      width: Platform.OS === 'ios' ? PxToDp(130) : PxToDp(148),
    },
  },
};
const MainScreenNavigator = TabNavigator(Routes, TabConfig);

class RecentChatsScreen extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      selectedTab: 'Event',
      claimSale: false,
    };
  }

  componentDidMount() {
    this._HomeOpen();
    CookieManager.get('https://dms.autoforce.net/dealer/info', (err, cookie) => {
      // FIXME TODO: use config for cookie name
      if (cookie && cookie.msid) {
        msid = cookie.msid;
      } else {
        console.log('no cookie!');
      }
    });
  }

  componentWillUnmount() {
    this._closeWs();
  }

  _closeWs() {
    if (homeWs) {
      homeWs.close();
      homeWs = null;
    }
  }
  _setModalSale(visible) {
    this.setState({ claimSale: visible });
  }

  claimRequest() {
    this.setState({ claimSale: false });
    this.props.navigator.resetTo({
      name: 'Login',
      component: Login,
    });
  }

  _HomeOpen() {
    homeWs = new WebSocket(homeWS_URL);
    homeWs.onopen = (e) => {
      console.log('open', e);
    };
    // 返回
    homeWs.onmessage = (e) => {
      const $this = this;
      if (e.type === 'message') {
        if (e.data[0] === '{') {
          const data = JSON.parse(e.data);
          const saleChanceData = $this.props.saleChanceData;
          const myCustomerData = $this.props.myCustomerData;
          if (msid === data.msid) { // 账号已退出，重新登录
            this.setState({ claimSale: true });
          }
          if (data.offline) {
            if (saleChanceData) {
              const index = _.findIndex(saleChanceData, o => o.id === data.offline.id);
              if (index > -1) {
                this.props.dispatch(fetchSaleList(1, true, false, 1, 0, 0, 0, 0));
              }
            }
            if (myCustomerData) {
              const index = _.findIndex(myCustomerData, o => o.id === data.offline.id);
              if (index > -1) {
                this.props.dispatch(fetchMyCustomerList(1, true,
                  false, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, ''));
              }
            }
          } else if (data.online) {
            if (saleChanceData) {
              const index = _.findIndex(saleChanceData, o => o.id === data.online.uid);
              if (index > -1) {
                this.props.dispatch(fetchSaleList(1, true, false, 1, 0, 0, 0, 0, ''));
              }
            }
            if (myCustomerData) {
              const index = _.findIndex(myCustomerData, o => o.id === data.online.uid);
              if (index > -1) {
                this.props.dispatch(fetchMyCustomerList(1, true, false, 1, 0,
                  0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, ''));
              }
            }
          }
        }
      }
    };

    homeWs.onerror = (e) => {
      console.log('websocket onerror', e);
    };

    homeWs.onclose = (e) => {
      console.log('websocket onclose', e.code, e.reason);
    };
  }

  saleFilter() {
    const dispatch = this.props.dispatch;
    let tabComponent = SaleChanceFilter;
    if (pageIndex === 1) {
      tabComponent = MyCustomerFilter;
    } else if (pageIndex === 2) {
      tabComponent = OtherCustomerFilter;
    } else if (pageIndex === 3) {
      tabComponent = ChanelFilter;
    } else {
      tabComponent = SaleChanceFilter;
    }
    this.props.navigator.push({
      component: tabComponent,
      passProps: { dispatch },
    });
  }

  render() {
    console.log(this.props);
    return (
      <View style={[style.wrrap, style.flex]}>
        <View style={[style.header, style.row]}>
          <View style={[style.topL]} />
          <View style={style.topC}>
            <Text style={[style.title]}>线索</Text>
          </View>
          <TouchableOpacity style={[style.topR]} onPress={() => this.saleFilter()}>
            <View style={style.row}>
              <Text style={style.filterT}>筛选</Text>
              <Image style={style.filterImg} source={require('../../img/home/filter.png')} />
            </View>
          </TouchableOpacity>
        </View>
        <MainScreenNavigator
          screenProps={this.props}
          onNavigationStateChange={(
            lastState, newState, action) => {
            pageIndex = newState.index;
            console.log('pageIndex=', pageIndex);
            console.log('lastState=', lastState);
            console.log('newState=', newState);
            console.log('action=', action);
          }
          }
        />
        <Modalext
          style={[style.flex, style.modalBg]}
          onRequestClose={() => this._setModalSale(false)}
          animationType={'slide'} transparent visible={this.state.claimSale}
        >

          <View style={[style.bgColor]}>
            <View style={style.modal}>
              <View style={[style.modalTitle]}>
                <Text style={style.modalTitelText}>提示</Text>
                <Text style={[style.modalContentText, style.modalTextTop]}>
                  账号已在其他移动设备上登陆，
                </Text>
                <Text style={style.modalContentText}>账号已退出。</Text>
              </View>
              <View style={[style.row, style.modalBtn]}>
                <TouchableOpacity
                  style={style.rectangle}
                  onPress={() => this.claimRequest()}
                >
                  <Text style={style.commintText}>确定</Text>
                </TouchableOpacity>
              </View>
            </View>
          </View>
        </Modalext>
      </View>
    );
  }
}
const style = StyleSheet.create({
  flex: {
    flex: 1,
    backgroundColor: '#F5F5F5',
  },
  wrrap: {
    marginTop: Platform.OS === 'ios' ? 20 : 0,
  },
  row: {
    flexDirection: 'row',
  },
  header: {
    height: PxToDp(44),
    backgroundColor: '#fff',
  },
  topL: {
    flex: 1,
  },
  topC: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    height: PxToDp(44),
  },
  topR: {
    flex: 1,
    alignItems: 'flex-end',
    justifyContent: 'center',
    paddingRight: PxToDp(9),
  },
  title: {
    fontFamily: FontFamilys(),
    fontSize: PxToDp(18),
    color: '#121212',
  },
  filterT: {
    fontFamily: FontFamilys(),
    fontSize: PxToDp(14),
    color: '#418cff',
    marginRight: PxToDp(4),
  },
  filterImg: {
    marginTop: PxToDp(3),
  },
  bgColor: {
    backgroundColor: 'transparent',
    alignItems: 'center',
    justifyContent: 'center',
    borderColor: '#F65252',
    height: '100%',
  },
  modalTitle: {
    marginTop: PxToDp(24),
    alignItems: 'center',
  },
  modalTitelText: {
    fontFamily: FontFamilys(),
    fontSize: PxToDp(20),
    color: '#333333',
  },
  modalContentText: {
    fontFamily: FontFamilys(),
    fontSize: PxToDp(16),
    color: '#333333',
  },
  modalTextTop: {
    marginTop: PxToDp(30),
  },
  modalBtn: {
    height: PxToDp(50),
    marginTop: PxToDp(40),
    width: PxToDp(300),
    justifyContent: 'center',
  },
  rectangle: {
    width: PxToDp(152),
    height: PxToDp(38),
    borderRadius: PxToDp(100),
    borderStyle: 'solid',
    borderWidth: PxToDp(1),
    borderColor: '#458fff',
    justifyContent: 'center',
    alignItems: 'center',
  },
  commintText: {
    fontFamily: FontFamilys(),
    fontSize: PxToDp(16),
    color: '#458fff',
  },
  modal: {
    height: PxToDp(220),
    backgroundColor: '#fff',
    width: PxToDp(300),
    borderRadius: PxToDp(2),
    borderColor: '#F65252',
    borderTopWidth: PxToDp(3),
    borderStyle: 'solid',
  },
  modalBg: {
    backgroundColor: 'transparent',
  },
});

export default RecentChatsScreen;
